import sys
import pytesseract
import keyboard
import pyautogui
from PyQt5.Qt import QApplication, QMainWindow
import serial.tools.list_ports
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QIcon

import PioneerOCR


class MainWindow(PioneerOCR.Ui_PioneerOCRUI, QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        self.regionButton.clicked.connect(self.regionset)
        self.OCRButton.clicked.connect(self.ocrbtn)
        self.sendButton.clicked.connect(self.sendbtn)
        self.comsetButton.clicked.connect(self.comset)
        self.saveButton.clicked.connect(self.saveconfig)
        self.showButton.clicked.connect(self.showbtn)

        self.UText = ""
        self.area = []
        self.sendFlag = False
        self.ocrFlag = False
        self.res = ""
        self.baud = 115200
        self.com = "COM1"
        self.ser = None
        self.ports_list = []
        self.res_od = ""
        self.showFlag = True


        self.comscan()
        self.loadconfig()
        self.prt("按ALT记录鼠标位置，选择区域")

        self.timer = QTimer(self)  # 创建计时器对象
        self.timer.timeout.connect(self.ocr_send)  # 设置计时器要执行的槽函数

    def prt(self, text):
        self.UEdit.append(text)
        self.UEdit.moveCursor(self.UEdit.textCursor().End)

    def regionset(self):
        try:
            keyboard.wait('ALT')
            x0, y0 = pyautogui.position()  # 返回鼠标的坐标
            self.prt("起始位置：" + str(x0) + "," + str(y0))
            keyboard.wait('ALT')
            x1, y1 = pyautogui.position()  # 返回鼠标的坐标
            self.prt("结束位置：" + str(x1) + "," + str(y1))
            if x1 - x0 < 1 or y1 - y0 < 1:
                self.prt("请重新选定")
                return
            self.area = [x0, y0, x1 - x0 + 1, y1 - y0 + 1]
            self.coordinateEdit.setText(str(self.area))
        except:
            return

    def ocrbtn(self):
        self.ocrFlag = not self.ocrFlag
        if self.ocrFlag:
            self.OCRButton.setText("停止获取")
            print("开始获取")
            self.timer.start()  # 开始计时器
            print("开始获取")
            self.prt("开始获取")
        else:
            self.OCRButton.setText("开始获取")
            self.timer.stop()  # 停止计时器
            self.prt("停止获取")

    def sendbtn(self):
        self.sendFlag = not self.sendFlag
        if self.sendFlag:
            self.sendButton.setText("停止发送")
            self.prt("开始发送")
        else:
            self.sendButton.setText("开始发送")
            self.prt("停止发送")

    def showbtn(self):
        self.showFlag = not self.showFlag
        if self.showFlag:
            self.showButton.setText("关闭显示")
            self.prt("打开显示")
        else:
            self.showButton.setText("打开显示")
            self.prt("关闭显示")

    def saveconfig(self):
        config = self.com + "\n" + str(self.baud) + "\n" + str(self.area)
        with open('config.txt', 'w') as f:
            f.write(config)
        self.prt("设置已保存")

    def loadconfig(self):
        try:
            file = open('config.txt', 'r')  # 打开文件
            cfg_data = file.readlines()  # 读取所有行

            self.baud = int(cfg_data[1].replace('\n', ''))
            self.com = cfg_data[0].replace('\n', '')
            self.baudEdit.setText(str(self.baud))

            area = cfg_data[2].replace('\n', '').replace('[', '').replace(']', '').split(', ')
            if len(area) == 4:
                self.area = [int(area[0]), int(area[1]), int(area[2]), int(area[3])]
                self.coordinateEdit.setText(str(self.area))
            self.prt("已加载设置")
            #print("串口:" + self.com + " 波特率:" + str(self.baud))  # 输出串口号
            #print(self.area)
        except:
            return

    def comscan(self):
        self.ports_list = list(serial.tools.list_ports.comports())
        if len(self.ports_list) <= 0:
            #print("无串口设备。")
            self.prt("无串口设备。")
        else:
            #print("可用的串口设备如下：")
            self.prt("可用的端口如下：")
            for comport in self.ports_list:
                self.comBox.addItem(list(comport)[0])
                #print(list(comport)[0], list(comport)[1])
                self.prt(str(list(comport)[0])+str(list(comport)[1]))

    def comset(self):
        self.com = self.comBox.currentText()
        self.baud = int(self.baudEdit.text())
        try:
            self.ser = serial.Serial(self.com, self.baud)  # 打开COM，将波特率配置，其余参数使用默认值
            if self.ser.isOpen():  # 判断串口是否成功打开
                self.prt("连接到串口:" + self.ser.name + " 波特率:" + str(self.baud))  # 输出串口号
        except:
            self.prt("连接失败")

    def ocr_send(self):
        if self.ocrFlag and self.area:
            try:
                img = pyautogui.screenshot(region=self.area)  # x,y,w,h
                #img.save('screenshot.png')
                # img = Image.open('test.png')
                # config = r'--oem 3 --psm 6 outputbase digits'  #
                config0 = r'-c tessedit_char_whitelist=0123456789 --psm 6'  # 使用白名单 仅数字
                self.res = pytesseract.image_to_string(img, config=config0)
                self.res = str(int(self.res))
            except:
                self.prt("检测失败")
                self.res = self.res_od

            #print("res:"+self.res)
            self.length = len(self.res)
            # print("len:"+str(length))
            if self.length > 5 or self.length < 2:
                self.res = self.res_od
            self.res_od = self.res

            if self.sendFlag:
                self.serial_send()
            if self.showFlag:
                self.resprocess()
                self.dbmEdit.setText("-" + self.res + " dBm")
            #print("res_p:"+self.res)

    def resprocess(self):
        try:
            # RSRP
            if self.res[0] == "1":
                self.res = str(int(self.res) / (10 ** (self.length - 3)))
            else:
                self.res = str(int(self.res) / (10 ** (self.length - 2)))
            # SINR

        except:
            self.res = self.res_od

    def serial_send(self):
        if self.ser:
            if self.length == 3:
                res = str(12800 - int(self.res) * 10)
            elif self.length == 2:
                res = str(12800 - int(self.res) * 100)
            else:
                res = str(12800 - int(self.res))
            send = "@" + res + "#"
            #print(send)
            write_len = self.ser.write(send.encode('utf-8'))
            #print("串口发出{}个字节。".format(write_len))
        else:
            self.prt("串口未连接")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.setWindowTitle("PioneerOCR")
    mainWindow.setWindowIcon(QIcon("./icon1.ico"))
    mainWindow.show()
    sys.exit(app.exec_())
